package com.ljl.mvvmdemo.net

import com.ljl.mvvmdemo.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 派单请求类
 * created by luojialun on 2024/10/12
 */
class NetManageBase private constructor() {

    private var retrofit: Retrofit
    private val CONNECT_TIME_OUT = 10L

    companion object {

        @Volatile
        private var instance: NetManageBase? = null

        fun getInstance(): NetManageBase {
            return instance ?: synchronized(this) {
                instance ?: NetManageBase().also { instance = it }
            }
        }

    }

    init {
        val httpLoggingInterceptor = HttpLoggingInterceptor().apply {
            level = if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor.Level.BODY
            } else {
                HttpLoggingInterceptor.Level.NONE
            }
        }

        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(LoggingInterceptor())
            .addInterceptor(httpLoggingInterceptor)
            .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
            .build()

        retrofit = Retrofit.Builder().baseUrl(HttpConstants.BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun <S> create(service: Class<S>): S {
        return retrofit.create(service)
    }

}